package com.starsea.book.ui.newpage.utils

import android.R
import android.annotation.TargetApi
import android.app.Activity
import android.content.Context
import android.content.res.Resources
import android.graphics.Color
import android.os.Build.*
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import android.widget.LinearLayout
import androidx.annotation.ColorInt
import androidx.annotation.IntRange
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.drawerlayout.widget.DrawerLayout
import java.lang.reflect.Field

/**
 * Function: 状态栏工具类(状态栏文字颜色)
 * Description:
 * 1、修改状态栏黑白字 功能逻辑--参考 https://github.com/QMUI/QMUI_Android  QMUIStatusBarHelper类
 */
object StatusBarUtil {
  const val STATUS_BAR_TYPE_DEFAULT = 1
  const val STATUS_BAR_TYPE_MI_UI = 1
  const val STATUS_BAR_TYPE_FLY_ME = 2
  const val STATUS_BAR_TYPE_ANDROID_M = 3

  /**
   * 设置状态栏浅色模式--黑色字体图标，
   *
   * @param activity
   * @return
   */
  fun setStatusBarLightMode(activity: Activity): Int {
    var result = STATUS_BAR_TYPE_DEFAULT
    if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
      //MIUI 9版本开始状态栏文字颜色恢复为系统原生方案-为防止反复修改先进行6.0方案
      if (setStatusBarModeForAndroidM(activity.getWindow(), true)) {
        result = STATUS_BAR_TYPE_ANDROID_M
      }
      if (setStatusBarModeForMIUI(activity.getWindow(), true)) {
        result = STATUS_BAR_TYPE_MI_UI
      } else if (setStatusBarModeForFlyMe(activity.getWindow(), true)) {
        result = STATUS_BAR_TYPE_FLY_ME
      }
    }
    return result
  }

  /**
   * 设置状态栏深色模式--白色字体图标，
   *
   * @param activity
   * @return
   */
  fun setStatusBarDarkMode(activity: Activity): Int {
    var result = STATUS_BAR_TYPE_DEFAULT
    if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
      //MIUI 9版本开始状态栏文字颜色恢复为系统原生方案-为防止反复修改先进行6.0方案
      if (setStatusBarModeForAndroidM(activity.getWindow(), false)) {
        result = STATUS_BAR_TYPE_ANDROID_M
      }
      if (setStatusBarModeForMIUI(activity.getWindow(), false)) {
        result = STATUS_BAR_TYPE_MI_UI
      } else if (setStatusBarModeForFlyMe(activity.getWindow(), false)) {
        result = STATUS_BAR_TYPE_FLY_ME
      }
    }
    return result
  }

  /**
   * 设置状态栏字体图标为深色，需要MIUIV6以上
   *
   * @param window   需要设置的窗口
   * @param darkText 是否把状态栏字体及图标颜色设置为深色
   * @return boolean 成功执行返回true
   */
  private fun setStatusBarModeForMIUI(window: Window?, darkText: Boolean): Boolean {
    var result = false
    if (window != null) {
      val clazz: Class<*> = window.javaClass
      try {
        var darkModeFlag = 0
        val layoutParams = Class.forName("android.view.MiuiWindowManager\$LayoutParams")
        val field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE")
        darkModeFlag = field.getInt(layoutParams)
        val extraFlagField = clazz.getMethod(
          "setExtraFlags",
          Int::class.javaPrimitiveType,
          Int::class.javaPrimitiveType
        )
        if (darkText) {
          extraFlagField.invoke(window, darkModeFlag, darkModeFlag) //状态栏透明且黑色字体
        } else {
          extraFlagField.invoke(window, 0, darkModeFlag) //清除黑色字体
        }
        result = true
      } catch (e: Exception) {
      }
    }
    return result
  }

  /**
   * 设置状态栏图标为深色和魅族特定的文字风格
   * 可以用来判断是否为Flyme用户
   *
   * @param window   需要设置的窗口
   * @param darkText 是否把状态栏字体及图标颜色设置为深色
   * @return boolean 成功执行返回true
   */
  private fun setStatusBarModeForFlyMe(window: Window?, darkText: Boolean): Boolean {
    var result = false
    if (window != null) {
      try {
        val lp: WindowManager.LayoutParams = window.attributes
        val darkFlag: Field = WindowManager.LayoutParams::class.java
          .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON")
        val meizuFlags: Field = WindowManager.LayoutParams::class.java
          .getDeclaredField("meizuFlags")
        darkFlag.isAccessible = true
        meizuFlags.isAccessible = true
        val bit = darkFlag.getInt(null)
        var value = meizuFlags.getInt(lp)
        value = if (darkText) {
          value or bit
        } else {
          value and bit.inv()
        }
        meizuFlags.setInt(lp, value)
        window.attributes = lp
        result = true
      } catch (e: Exception) {
      }
    }
    return result
  }

  /**
   * 设置原生Android 6.0以上系统状态栏
   *
   * @param window
   * @param darkText 是否把状态栏字体及图标颜色设置为深色
   * @return
   */
  private fun setStatusBarModeForAndroidM(window: Window, darkText: Boolean): Boolean {
    var result = false
    if (VERSION.SDK_INT >= VERSION_CODES.M) {
      var systemUi =
        if (darkText) View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        else View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
      systemUi = changeStatusBarModeRetainFlag(window, systemUi)
      window.decorView.systemUiVisibility = systemUi
      result = true
    }
    return result
  }

  val isSupportStatusBarFontChange: Boolean
    /**
     * 判断系统是否支持状态栏文字及图标颜色变化
     *
     * @return
     */
    get() = RomUtil.mIUIVersionCode >= 6 || RomUtil.flymeVersionCode >= 4 || VERSION.SDK_INT >= VERSION_CODES.M

  /**
   * 获取状态栏高度
   *
   * @return
   */

  fun getStatusBarHeight(): Int {
    var result = 0
    val resourceId = Resources.getSystem().getIdentifier("status_bar_height", "dimen", "android")
    if (resourceId > 0) {
      result = Resources.getSystem().getDimensionPixelSize(resourceId)
    }
    return result
  }

  @TargetApi(23)
  private fun changeStatusBarModeRetainFlag(window: Window, out: Int): Int {
    var out = out
    out = retainSystemUiFlag(window, out, View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
    out = retainSystemUiFlag(window, out, View.SYSTEM_UI_FLAG_FULLSCREEN)
    out = retainSystemUiFlag(window, out, View.SYSTEM_UI_FLAG_HIDE_NAVIGATION)
    out = retainSystemUiFlag(window, out, View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
    out = retainSystemUiFlag(window, out, View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
    out = retainSystemUiFlag(window, out, View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
    return out
  }

  fun retainSystemUiFlag(window: Window, out: Int, type: Int): Int {
    var out = out
    val now = window.decorView.systemUiVisibility
    if (now and type == type) {
      out = out or type
    }
    return out
  }

  const val DEFAULT_STATUS_BAR_ALPHA = 112
  private val FAKE_STATUS_BAR_VIEW_ID: Int = 91092
  private val FAKE_TRANSLUCENT_VIEW_ID: Int = 92139
  private const val TAG_KEY_HAVE_SET_OFFSET = -123

  /**
   * 设置状态栏颜色
   *
   * @param activity 需要设置的 activity
   * @param color    状态栏颜色值
   */
  fun setColor(activity: Activity, @ColorInt color: Int) {
    setColor(activity, color, DEFAULT_STATUS_BAR_ALPHA)
  }

  /**
   * 设置状态栏颜色
   *
   * @param activity       需要设置的activity
   * @param color          状态栏颜色值
   * @param statusBarAlpha 状态栏透明度
   */
  fun setColor(
    activity: Activity,
    @ColorInt color: Int,
    @IntRange(from = 0, to = 255) statusBarAlpha: Int
  ) {
    if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
      activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
      activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
      activity.getWindow().setStatusBarColor(calculateStatusColor(color, statusBarAlpha))
    } else if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
      activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
      val decorView: ViewGroup = activity.getWindow().getDecorView() as ViewGroup
      val fakeStatusBarView: View = decorView.findViewById<View>(FAKE_STATUS_BAR_VIEW_ID)
      if (fakeStatusBarView != null) {
        if (fakeStatusBarView.visibility == View.GONE) {
          fakeStatusBarView.visibility = View.VISIBLE
        }
        fakeStatusBarView.setBackgroundColor(calculateStatusColor(color, statusBarAlpha))
      } else {
        decorView.addView(createStatusBarView(activity, color, statusBarAlpha))
      }
      setRootView(activity)
    }
  }

  /**
   * 为滑动返回界面设置状态栏颜色
   *
   * @param activity 需要设置的activity
   * @param color    状态栏颜色值
   */
  fun setColorForSwipeBack(activity: Activity, color: Int) {
    setColorForSwipeBack(activity, color, DEFAULT_STATUS_BAR_ALPHA)
  }

  /**
   * 为滑动返回界面设置状态栏颜色
   *
   * @param activity       需要设置的activity
   * @param color          状态栏颜色值
   * @param statusBarAlpha 状态栏透明度
   */
  fun setColorForSwipeBack(
    activity: Activity, @ColorInt color: Int,
    @IntRange(from = 0, to = 255) statusBarAlpha: Int
  ) {
    if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
      val contentView: ViewGroup = activity.findViewById<ViewGroup>(R.id.content)
      val rootView: View = contentView.getChildAt(0)
      val statusBarHeight = getStatusBarHeight(activity)
      if (rootView != null && rootView is CoordinatorLayout) {
        val coordinatorLayout: CoordinatorLayout = rootView as CoordinatorLayout
        if (VERSION.SDK_INT < VERSION_CODES.LOLLIPOP) {
          coordinatorLayout.setFitsSystemWindows(false)
          contentView.setBackgroundColor(calculateStatusColor(color, statusBarAlpha))
          val isNeedRequestLayout: Boolean = contentView.getPaddingTop() < statusBarHeight
          if (isNeedRequestLayout) {
            contentView.setPadding(0, statusBarHeight, 0, 0)
            coordinatorLayout.post(Runnable { coordinatorLayout.requestLayout() })
          }
        } else {
          coordinatorLayout.setStatusBarBackgroundColor(calculateStatusColor(color, statusBarAlpha))
        }
      } else {
        contentView.setPadding(0, statusBarHeight, 0, 0)
        contentView.setBackgroundColor(calculateStatusColor(color, statusBarAlpha))
      }
      setTransparentForWindow(activity)
    }
  }

  /**
   * 设置状态栏纯色 不加半透明效果
   *
   * @param activity 需要设置的 activity
   * @param color    状态栏颜色值
   */
  fun setColorNoTranslucent(activity: Activity, @ColorInt color: Int) {
    setColor(activity, color, 0)
  }

  /**
   * 设置状态栏颜色(5.0以下无半透明效果,不建议使用)
   *
   * @param activity 需要设置的 activity
   * @param color    状态栏颜色值
   */
  @Deprecated("")
  fun setColorDiff(activity: Activity, @ColorInt color: Int) {
    if (VERSION.SDK_INT < VERSION_CODES.KITKAT) {
      return
    }
    transparentStatusBar(activity)
    val contentView: ViewGroup = activity.findViewById<ViewGroup>(R.id.content)
    // 移除半透明矩形,以免叠加
    val fakeStatusBarView: View = contentView.findViewById<View>(FAKE_STATUS_BAR_VIEW_ID)
    if (fakeStatusBarView != null) {
      if (fakeStatusBarView.visibility == View.GONE) {
        fakeStatusBarView.visibility = View.VISIBLE
      }
      fakeStatusBarView.setBackgroundColor(color)
    } else {
      contentView.addView(createStatusBarView(activity, color))
    }
    setRootView(activity)
  }

  /**
   * 使状态栏半透明
   *
   *
   * 适用于图片作为背景的界面,此时需要图片填充到状态栏
   *
   * @param activity 需要设置的activity
   */
  fun setTranslucent(activity: Activity) {
    setTranslucent(activity, DEFAULT_STATUS_BAR_ALPHA)
  }

  /**
   * 使状态栏半透明
   *
   *
   * 适用于图片作为背景的界面,此时需要图片填充到状态栏
   *
   * @param activity       需要设置的activity
   * @param statusBarAlpha 状态栏透明度
   */
  fun setTranslucent(activity: Activity, @IntRange(from = 0, to = 255) statusBarAlpha: Int) {
    if (VERSION.SDK_INT < VERSION_CODES.KITKAT) {
      return
    }
    setTransparent(activity)
    addTranslucentView(activity, statusBarAlpha)
  }

  /**
   * 针对根布局是 CoordinatorLayout, 使状态栏半透明
   *
   *
   * 适用于图片作为背景的界面,此时需要图片填充到状态栏
   *
   * @param activity       需要设置的activity
   * @param statusBarAlpha 状态栏透明度
   */
  fun setTranslucentForCoordinatorLayout(
    activity: Activity,
    @IntRange(from = 0, to = 255) statusBarAlpha: Int
  ) {
    if (VERSION.SDK_INT < VERSION_CODES.KITKAT) {
      return
    }
    transparentStatusBar(activity)
    addTranslucentView(activity, statusBarAlpha)
  }

  /**
   * 设置状态栏全透明
   *
   * @param activity 需要设置的activity
   */
  fun setTransparent(activity: Activity) {
    if (VERSION.SDK_INT < VERSION_CODES.KITKAT) {
      return
    }
    transparentStatusBar(activity)
    setRootView(activity)
  }

  /**
   * 使状态栏透明(5.0以上半透明效果,不建议使用)
   *
   *
   * 适用于图片作为背景的界面,此时需要图片填充到状态栏
   *
   * @param activity 需要设置的activity
   */
  @Deprecated("")
  fun setTranslucentDiff(activity: Activity) {
    if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
      // 设置状态栏透明
      activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
      setRootView(activity)
    }
  }

  /**
   * 为DrawerLayout 布局设置状态栏变色
   *
   * @param activity     需要设置的activity
   * @param drawerLayout DrawerLayout
   * @param color        状态栏颜色值
   */
  fun setColorForDrawerLayout(
    activity: Activity,
    drawerLayout: DrawerLayout,
    @ColorInt color: Int
  ) {
    setColorForDrawerLayout(activity, drawerLayout, color, DEFAULT_STATUS_BAR_ALPHA)
  }

  /**
   * 为DrawerLayout 布局设置状态栏颜色,纯色
   *
   * @param activity     需要设置的activity
   * @param drawerLayout DrawerLayout
   * @param color        状态栏颜色值
   */
  fun setColorNoTranslucentForDrawerLayout(
    activity: Activity,
    drawerLayout: DrawerLayout,
    @ColorInt color: Int
  ) {
    setColorForDrawerLayout(activity, drawerLayout, color, 0)
  }

  /**
   * 为DrawerLayout 布局设置状态栏变色
   *
   * @param activity       需要设置的activity
   * @param drawerLayout   DrawerLayout
   * @param color          状态栏颜色值
   * @param statusBarAlpha 状态栏透明度
   */
  fun setColorForDrawerLayout(
    activity: Activity, drawerLayout: DrawerLayout, @ColorInt color: Int,
    @IntRange(from = 0, to = 255) statusBarAlpha: Int
  ) {
    if (VERSION.SDK_INT < VERSION_CODES.KITKAT) {
      return
    }
    if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
      activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
      activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
      activity.getWindow().setStatusBarColor(Color.TRANSPARENT)
    } else {
      activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
    }
    // 生成一个状态栏大小的矩形
    // 添加 statusBarView 到布局中
    val contentLayout: ViewGroup = drawerLayout.getChildAt(0) as ViewGroup
    val fakeStatusBarView: View = contentLayout.findViewById<View>(FAKE_STATUS_BAR_VIEW_ID)
    if (fakeStatusBarView != null) {
      if (fakeStatusBarView.visibility == View.GONE) {
        fakeStatusBarView.visibility = View.VISIBLE
      }
      fakeStatusBarView.setBackgroundColor(color)
    } else {
      contentLayout.addView(createStatusBarView(activity, color), 0)
    }
    // 内容布局不是 LinearLayout 时,设置padding top
    if (contentLayout !is LinearLayout && contentLayout.getChildAt(1) != null) {
      contentLayout.getChildAt(1)
        .setPadding(
          contentLayout.getPaddingLeft(),
          getStatusBarHeight(activity) + contentLayout.getPaddingTop(),
          contentLayout.getPaddingRight(),
          contentLayout.getPaddingBottom()
        )
    }
    // 设置属性
    setDrawerLayoutProperty(drawerLayout, contentLayout)
    addTranslucentView(activity, statusBarAlpha)
  }

  /**
   * 设置 DrawerLayout 属性
   *
   * @param drawerLayout              DrawerLayout
   * @param drawerLayoutContentLayout DrawerLayout 的内容布局
   */
  private fun setDrawerLayoutProperty(
    drawerLayout: DrawerLayout,
    drawerLayoutContentLayout: ViewGroup
  ) {
    val drawer: ViewGroup = drawerLayout.getChildAt(1) as ViewGroup
    drawerLayout.setFitsSystemWindows(false)
    drawerLayoutContentLayout.setFitsSystemWindows(false)
    drawerLayoutContentLayout.setClipToPadding(true)
    drawer.setFitsSystemWindows(false)
  }

  /**
   * 为DrawerLayout 布局设置状态栏变色(5.0以下无半透明效果,不建议使用)
   *
   * @param activity     需要设置的activity
   * @param drawerLayout DrawerLayout
   * @param color        状态栏颜色值
   */
  @Deprecated("")
  fun setColorForDrawerLayoutDiff(
    activity: Activity,
    drawerLayout: DrawerLayout,
    @ColorInt color: Int
  ) {
    if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
      activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
      // 生成一个状态栏大小的矩形
      val contentLayout: ViewGroup = drawerLayout.getChildAt(0) as ViewGroup
      val fakeStatusBarView: View = contentLayout.findViewById<View>(FAKE_STATUS_BAR_VIEW_ID)
      if (fakeStatusBarView != null) {
        if (fakeStatusBarView.visibility == View.GONE) {
          fakeStatusBarView.visibility = View.VISIBLE
        }
        fakeStatusBarView.setBackgroundColor(calculateStatusColor(color, DEFAULT_STATUS_BAR_ALPHA))
      } else {
        // 添加 statusBarView 到布局中
        contentLayout.addView(createStatusBarView(activity, color), 0)
      }
      // 内容布局不是 LinearLayout 时,设置padding top
      if (contentLayout !is LinearLayout && contentLayout.getChildAt(1) != null) {
        contentLayout.getChildAt(1).setPadding(0, getStatusBarHeight(activity), 0, 0)
      }
      // 设置属性
      setDrawerLayoutProperty(drawerLayout, contentLayout)
    }
  }

  /**
   * 为 DrawerLayout 布局设置状态栏透明
   *
   * @param activity     需要设置的activity
   * @param drawerLayout DrawerLayout
   */
  fun setTranslucentForDrawerLayout(activity: Activity, drawerLayout: DrawerLayout) {
    setTranslucentForDrawerLayout(activity, drawerLayout, DEFAULT_STATUS_BAR_ALPHA)
  }

  /**
   * 为 DrawerLayout 布局设置状态栏透明
   *
   * @param activity     需要设置的activity
   * @param drawerLayout DrawerLayout
   */
  fun setTranslucentForDrawerLayout(
    activity: Activity, drawerLayout: DrawerLayout,
    @IntRange(from = 0, to = 255) statusBarAlpha: Int
  ) {
    if (VERSION.SDK_INT < VERSION_CODES.KITKAT) {
      return
    }
    setTransparentForDrawerLayout(activity, drawerLayout)
    addTranslucentView(activity, statusBarAlpha)
  }

  /**
   * 为 DrawerLayout 布局设置状态栏透明
   *
   * @param activity     需要设置的activity
   * @param drawerLayout DrawerLayout
   */
  fun setTransparentForDrawerLayout(activity: Activity, drawerLayout: DrawerLayout) {
    if (VERSION.SDK_INT < VERSION_CODES.KITKAT) {
      return
    }
    if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
      activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
      activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
      activity.getWindow().setStatusBarColor(Color.TRANSPARENT)
    } else {
      activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
    }
    val contentLayout: ViewGroup = drawerLayout.getChildAt(0) as ViewGroup
    // 内容布局不是 LinearLayout 时,设置padding top
    if (contentLayout !is LinearLayout && contentLayout.getChildAt(1) != null) {
      contentLayout.getChildAt(1).setPadding(0, getStatusBarHeight(activity), 0, 0)
    }

    // 设置属性
    setDrawerLayoutProperty(drawerLayout, contentLayout)
  }

  /**
   * 为 DrawerLayout 布局设置状态栏透明(5.0以上半透明效果,不建议使用)
   *
   * @param activity     需要设置的activity
   * @param drawerLayout DrawerLayout
   */
  @Deprecated("")
  fun setTranslucentForDrawerLayoutDiff(activity: Activity, drawerLayout: DrawerLayout) {
    if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
      // 设置状态栏透明
      activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
      // 设置内容布局属性
      val contentLayout: ViewGroup = drawerLayout.getChildAt(0) as ViewGroup
      contentLayout.setFitsSystemWindows(true)
      contentLayout.setClipToPadding(true)
      // 设置抽屉布局属性
      val vg: ViewGroup = drawerLayout.getChildAt(1) as ViewGroup
      vg.setFitsSystemWindows(false)
      // 设置 DrawerLayout 属性
      drawerLayout.setFitsSystemWindows(false)
    }
  }

  /**
   * 为头部是 ImageView 的界面设置状态栏全透明
   *
   * @param activity       需要设置的activity
   * @param needOffsetView 需要向下偏移的 View
   */
  fun setTransparentForImageView(activity: Activity, needOffsetView: View?) {
    setTranslucentForImageView(activity, 0, needOffsetView)
  }

  /**
   * 为头部是 ImageView 的界面设置状态栏透明(使用默认透明度)
   *
   * @param activity       需要设置的activity
   * @param needOffsetView 需要向下偏移的 View
   */
  fun setTranslucentForImageView(activity: Activity, needOffsetView: View?) {
    setTranslucentForImageView(activity, DEFAULT_STATUS_BAR_ALPHA, needOffsetView)
  }

  /**
   * 为头部是 ImageView 的界面设置状态栏透明
   *
   * @param activity       需要设置的activity
   * @param statusBarAlpha 状态栏透明度
   * @param needOffsetView 需要向下偏移的 View
   */
  fun setTranslucentForImageView(
    activity: Activity, @IntRange(from = 0, to = 255) statusBarAlpha: Int,
    needOffsetView: View?
  ) {
    if (VERSION.SDK_INT < VERSION_CODES.KITKAT) {
      return
    }
    setTransparentForWindow(activity)
    addTranslucentView(activity, statusBarAlpha)
    if (needOffsetView != null) {
      val haveSetOffset = needOffsetView.getTag(TAG_KEY_HAVE_SET_OFFSET)
      if (haveSetOffset != null && haveSetOffset as Boolean) {
        return
      }
      val layoutParams: ViewGroup.MarginLayoutParams =
        needOffsetView.layoutParams as ViewGroup.MarginLayoutParams
      layoutParams.setMargins(
        layoutParams.leftMargin, layoutParams.topMargin + getStatusBarHeight(activity),
        layoutParams.rightMargin, layoutParams.bottomMargin
      )
      needOffsetView.setTag(TAG_KEY_HAVE_SET_OFFSET, true)
    }
  }

  /**
   * 为 fragment 头部是 ImageView 的设置状态栏透明
   *
   * @param activity       fragment 对应的 activity
   * @param needOffsetView 需要向下偏移的 View
   */
  fun setTranslucentForImageViewInFragment(activity: Activity, needOffsetView: View?) {
    setTranslucentForImageViewInFragment(activity, DEFAULT_STATUS_BAR_ALPHA, needOffsetView)
  }

  /**
   * 为 fragment 头部是 ImageView 的设置状态栏透明
   *
   * @param activity       fragment 对应的 activity
   * @param needOffsetView 需要向下偏移的 View
   */
  fun setTransparentForImageViewInFragment(activity: Activity, needOffsetView: View?) {
    setTranslucentForImageViewInFragment(activity, 0, needOffsetView)
  }

  /**
   * 为 fragment 头部是 ImageView 的设置状态栏透明
   *
   * @param activity       fragment 对应的 activity
   * @param statusBarAlpha 状态栏透明度
   * @param needOffsetView 需要向下偏移的 View
   */
  fun setTranslucentForImageViewInFragment(
    activity: Activity, @IntRange(from = 0, to = 255) statusBarAlpha: Int,
    needOffsetView: View?
  ) {
    setTranslucentForImageView(activity, statusBarAlpha, needOffsetView)
    if (VERSION.SDK_INT >= VERSION_CODES.KITKAT && VERSION.SDK_INT < VERSION_CODES.LOLLIPOP) {
      clearPreviousSetting(activity)
    }
  }

  /**
   * 隐藏伪状态栏 View
   *
   * @param activity 调用的 Activity
   */
  fun hideFakeStatusBarView(activity: Activity) {
    val decorView: ViewGroup = activity.getWindow().getDecorView() as ViewGroup
    val fakeStatusBarView: View = decorView.findViewById<View>(FAKE_STATUS_BAR_VIEW_ID)
    if (fakeStatusBarView != null) {
      fakeStatusBarView.visibility = View.GONE
    }
    val fakeTranslucentView: View = decorView.findViewById<View>(FAKE_TRANSLUCENT_VIEW_ID)
    if (fakeTranslucentView != null) {
      fakeTranslucentView.visibility = View.GONE
    }
  }

  @TargetApi(VERSION_CODES.M)
  fun setLightMode(activity: Activity) {
    setMIUIStatusBarDarkIcon(activity, true)
    setMeizuStatusBarDarkIcon(activity, true)
    if (VERSION.SDK_INT >= VERSION_CODES.M) {
      activity.getWindow().getDecorView()
        .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
    }
  }

  @TargetApi(VERSION_CODES.M)
  fun setDarkMode(activity: Activity) {
    setMIUIStatusBarDarkIcon(activity, false)
    setMeizuStatusBarDarkIcon(activity, false)
    if (VERSION.SDK_INT >= VERSION_CODES.M) {
      activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE)
    }
  }

  /**
   * 修改 MIUI V6  以上状态栏颜色
   */
  private fun setMIUIStatusBarDarkIcon(activity: Activity, darkIcon: Boolean) {
    val clazz: Class<out Window> = activity.getWindow().javaClass
    try {
      val layoutParams = Class.forName("android.view.MiuiWindowManager\$LayoutParams")
      val field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE")
      val darkModeFlag = field.getInt(layoutParams)
      val extraFlagField =
        clazz.getMethod("setExtraFlags", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType)
      extraFlagField.invoke(activity.getWindow(), if (darkIcon) darkModeFlag else 0, darkModeFlag)
    } catch (e: Exception) {
      //e.printStackTrace();
    }
  }

  /**
   * 修改魅族状态栏字体颜色 Flyme 4.0
   */
  private fun setMeizuStatusBarDarkIcon(activity: Activity, darkIcon: Boolean) {
    try {
      val lp: WindowManager.LayoutParams = activity.getWindow().getAttributes()
      val darkFlag: Field =
        WindowManager.LayoutParams::class.java.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON")
      val meizuFlags: Field = WindowManager.LayoutParams::class.java.getDeclaredField("meizuFlags")
      darkFlag.isAccessible = true
      meizuFlags.isAccessible = true
      val bit = darkFlag.getInt(null)
      var value = meizuFlags.getInt(lp)
      value = if (darkIcon) {
        value or bit
      } else {
        value and bit.inv()
      }
      meizuFlags.setInt(lp, value)
      activity.getWindow().setAttributes(lp)
    } catch (e: Exception) {
      //e.printStackTrace();
    }
  }

  ///////////////////////////////////////////////////////////////////////////////////
  @TargetApi(VERSION_CODES.KITKAT)
  private fun clearPreviousSetting(activity: Activity) {
    val decorView: ViewGroup = activity.getWindow().getDecorView() as ViewGroup
    val fakeStatusBarView: View = decorView.findViewById<View>(FAKE_STATUS_BAR_VIEW_ID)
    if (fakeStatusBarView != null) {
      decorView.removeView(fakeStatusBarView)
      val rootView: ViewGroup =
        (activity.findViewById<View>(R.id.content) as ViewGroup).getChildAt(0) as ViewGroup
      rootView.setPadding(0, 0, 0, 0)
    }
  }

  /**
   * 添加半透明矩形条
   *
   * @param activity       需要设置的 activity
   * @param statusBarAlpha 透明值
   */
  private fun addTranslucentView(
    activity: Activity,
    @IntRange(from = 0, to = 255) statusBarAlpha: Int
  ) {
    val contentView: ViewGroup = activity.findViewById<ViewGroup>(R.id.content)
    val fakeTranslucentView: View = contentView.findViewById<View>(FAKE_TRANSLUCENT_VIEW_ID)
    if (fakeTranslucentView != null) {
      if (fakeTranslucentView.visibility == View.GONE) {
        fakeTranslucentView.visibility = View.VISIBLE
      }
      fakeTranslucentView.setBackgroundColor(Color.argb(statusBarAlpha, 0, 0, 0))
    } else {
      contentView.addView(createTranslucentStatusBarView(activity, statusBarAlpha))
    }
  }
  /**
   * 生成一个和状态栏大小相同的半透明矩形条
   *
   * @param activity 需要设置的activity
   * @param color    状态栏颜色值
   * @param alpha    透明值
   * @return 状态栏矩形条
   */
  /**
   * 生成一个和状态栏大小相同的彩色矩形条
   *
   * @param activity 需要设置的 activity
   * @param color    状态栏颜色值
   * @return 状态栏矩形条
   */
  private fun createStatusBarView(activity: Activity, @ColorInt color: Int, alpha: Int = 0): View {
    // 绘制一个和状态栏一样高的矩形
    val statusBarView = View(activity)
    val params: LinearLayout.LayoutParams =
      LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity))
    statusBarView.layoutParams = params
    statusBarView.setBackgroundColor(calculateStatusColor(color, alpha))
    statusBarView.id = FAKE_STATUS_BAR_VIEW_ID
    return statusBarView
  }

  /**
   * 设置根布局参数
   */
  private fun setRootView(activity: Activity) {
    val parent: ViewGroup = activity.findViewById<ViewGroup>(R.id.content)
    var i = 0
    val count: Int = parent.getChildCount()
    while (i < count) {
      val childView: View = parent.getChildAt(i)
      if (childView is ViewGroup) {
        childView.fitsSystemWindows = true
        (childView as ViewGroup).setClipToPadding(true)
      }
      i++
    }
  }

  /**
   * 设置透明
   */
  private fun setTransparentForWindow(activity: Activity) {
    if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
      activity.getWindow().setStatusBarColor(Color.TRANSPARENT)
      activity.getWindow()
        .getDecorView()
        .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
    } else if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
      activity.getWindow()
        .setFlags(
          WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
          WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
        )
    }
  }

  /**
   * 使状态栏透明
   */
  @TargetApi(VERSION_CODES.KITKAT)
  private fun transparentStatusBar(activity: Activity) {
    if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
      activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
      activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
      activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
      activity.getWindow().setStatusBarColor(Color.TRANSPARENT)
    } else {
      activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
    }
  }

  /**
   * 创建半透明矩形 View
   *
   * @param alpha 透明值
   * @return 半透明 View
   */
  private fun createTranslucentStatusBarView(activity: Activity, alpha: Int): View {
    // 绘制一个和状态栏一样高的矩形
    val statusBarView = View(activity)
    val params: LinearLayout.LayoutParams =
      LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity))
    statusBarView.layoutParams = params
    statusBarView.setBackgroundColor(Color.argb(alpha, 0, 0, 0))
    statusBarView.id = FAKE_TRANSLUCENT_VIEW_ID
    return statusBarView
  }

  /**
   * 获取状态栏高度
   *
   * @param context context
   * @return 状态栏高度
   */
  private fun getStatusBarHeight(context: Context): Int {
    // 获得状态栏高度
    val resourceId = context.resources.getIdentifier("status_bar_height", "dimen", "android")
    return context.resources.getDimensionPixelSize(resourceId)
  }

  /**
   * 计算状态栏颜色
   *
   * @param color color值
   * @param alpha alpha值
   * @return 最终的状态栏颜色
   */
  private fun calculateStatusColor(@ColorInt color: Int, alpha: Int): Int {
    if (alpha == 0) {
      return color
    }
    val a = 1 - alpha / 255f
    var red = color shr 16 and 0xff
    var green = color shr 8 and 0xff
    var blue = color and 0xff
    red = (red * a + 0.5).toInt()
    green = (green * a + 0.5).toInt()
    blue = (blue * a + 0.5).toInt()
    return 0xff shl 24 or (red shl 16) or (green shl 8) or blue
  }
}
